package library.client;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import library.stub.Author;
import library.stub.Book;

public class LibraryClientFrame extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private ButtonGroup bGroup;
	private JButton btnSend;
	private JRadioButton rdbtnSelect, rdbtnInsert, rdbtnDelete;
	private JTextPane textPane;
	private Style redStyle, blackStyle, greenStyle;
	private JScrollPane scrollPane;
	private JTextField textFieldFilter;
	private JTable table;
	private JTextField textFieldISDN;
	private JTextField textFieldTitle;
	private JTextField textFieldPublisher;
	private JTextField textFieldPrice;
	private JTextArea textAreaAuthors;

	private LibraryTableModel tableModel;
	private JTextField textFieldDay;

	// /**
	// * Launch the application.
	// */
	// public static void main(String[] args) {
	// EventQueue.invokeLater(new Runnable() {
	// public void run() {
	// try {
	// DictionaryClientFrame frame = new DictionaryClientFrame();
	// frame.setVisible(true);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
	// });
	// }

	public LibraryClientFrame() {
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 777, 513);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "Information",
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.setBounds(6, 196, 765, 91);
		contentPane.add(panel);
		panel.setLayout(new BorderLayout(0, 0));

		scrollPane = new JScrollPane();
		scrollPane
				.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

		panel.add(scrollPane);

		textPane = new JTextPane();
		textPane.setEditable(false);
		scrollPane.setViewportView(textPane);
		textPane.setMargin(new Insets(4, 4, 4, 4));
		redStyle = textPane.addStyle("Red style", null);
		StyleConstants.setForeground(redStyle, Color.RED);
		blackStyle = textPane.addStyle("Black style", null);
		StyleConstants.setForeground(blackStyle, Color.BLACK);
		greenStyle = textPane.addStyle("Green style", null);
		StyleConstants.setForeground(greenStyle, Color.GREEN);

		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "Option",
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_1.setBounds(6, 288, 92, 156);
		contentPane.add(panel_1);
		panel_1.setLayout(new GridLayout(3, 1, 0, 0));

		rdbtnSelect = new JRadioButton("Select");
		rdbtnSelect.setSelected(true);
		panel_1.add(rdbtnSelect);

		rdbtnDelete = new JRadioButton("Delete");
		panel_1.add(rdbtnDelete);

		rdbtnInsert = new JRadioButton("Insert");
		panel_1.add(rdbtnInsert);

		bGroup = new ButtonGroup();
		bGroup.add(rdbtnInsert);
		bGroup.add(rdbtnDelete);
		bGroup.add(rdbtnSelect);

		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new TitledBorder(null, "Values",
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_2.setBounds(104, 288, 667, 156);
		contentPane.add(panel_2);
		GridBagLayout gbl_panel_2 = new GridBagLayout();
		gbl_panel_2.columnWidths = new int[] { 0, 0, 0, 0, 0, 0 };
		gbl_panel_2.rowHeights = new int[] { 0, 0, 0, 0, 0 };
		gbl_panel_2.columnWeights = new double[] { 0.0, 1.0, 0.0, 0.0, 1.0,
				Double.MIN_VALUE };
		gbl_panel_2.rowWeights = new double[] { 1.0, 1.0, 0.0, 0.0,
				Double.MIN_VALUE };
		panel_2.setLayout(gbl_panel_2);

		JLabel lblIsdn = new JLabel("ISDN:");
		GridBagConstraints gbc_lblIsdn = new GridBagConstraints();
		gbc_lblIsdn.anchor = GridBagConstraints.EAST;
		gbc_lblIsdn.insets = new Insets(0, 0, 5, 5);
		gbc_lblIsdn.gridx = 0;
		gbc_lblIsdn.gridy = 0;
		panel_2.add(lblIsdn, gbc_lblIsdn);

		textFieldISDN = new JTextField();
		GridBagConstraints gbc_textFieldISDN = new GridBagConstraints();
		gbc_textFieldISDN.fill = GridBagConstraints.HORIZONTAL;
		gbc_textFieldISDN.insets = new Insets(0, 0, 5, 5);
		gbc_textFieldISDN.gridx = 1;
		gbc_textFieldISDN.gridy = 0;
		panel_2.add(textFieldISDN, gbc_textFieldISDN);
		textFieldISDN.setColumns(10);

		JLabel lblDate = new JLabel("Date:");
		GridBagConstraints gbc_lblDate = new GridBagConstraints();
		gbc_lblDate.anchor = GridBagConstraints.EAST;
		gbc_lblDate.insets = new Insets(0, 0, 5, 5);
		gbc_lblDate.gridx = 3;
		gbc_lblDate.gridy = 0;
		panel_2.add(lblDate, gbc_lblDate);

		JPanel panel_5 = new JPanel();
		GridBagConstraints gbc_panel_5 = new GridBagConstraints();
		gbc_panel_5.insets = new Insets(0, 0, 5, 0);
		gbc_panel_5.fill = GridBagConstraints.BOTH;
		gbc_panel_5.gridx = 4;
		gbc_panel_5.gridy = 0;
		panel_2.add(panel_5, gbc_panel_5);
		GridBagLayout gbl_panel_5 = new GridBagLayout();
		gbl_panel_5.columnWidths = new int[] { 0, 0 };
		gbl_panel_5.rowHeights = new int[] { 0, 0 };
		gbl_panel_5.columnWeights = new double[] { 1.0, 0.0 };
		gbl_panel_5.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
		panel_5.setLayout(gbl_panel_5);

		textFieldDay = new JTextField();
		textFieldDay.setSize(new Dimension(20, 0));
		GridBagConstraints gbc_textFieldDay = new GridBagConstraints();
		gbc_textFieldDay.fill = GridBagConstraints.HORIZONTAL;
		gbc_textFieldDay.insets = new Insets(0, 0, 0, 5);
		gbc_textFieldDay.gridx = 0;
		gbc_textFieldDay.gridy = 0;
		panel_5.add(textFieldDay, gbc_textFieldDay);
		textFieldDay.setColumns(10);

		JLabel lblddmmyyyy = new JLabel("[dd-mm-yyyy]");
		GridBagConstraints gbc_lblddmmyyyy = new GridBagConstraints();
		gbc_lblddmmyyyy.insets = new Insets(0, 0, 0, 5);
		gbc_lblddmmyyyy.anchor = GridBagConstraints.EAST;
		gbc_lblddmmyyyy.gridx = 1;
		gbc_lblddmmyyyy.gridy = 0;
		panel_5.add(lblddmmyyyy, gbc_lblddmmyyyy);

		JLabel lblTitle = new JLabel("Title:");
		GridBagConstraints gbc_lblTitle = new GridBagConstraints();
		gbc_lblTitle.anchor = GridBagConstraints.EAST;
		gbc_lblTitle.insets = new Insets(0, 0, 5, 5);
		gbc_lblTitle.gridx = 0;
		gbc_lblTitle.gridy = 1;
		panel_2.add(lblTitle, gbc_lblTitle);

		textFieldTitle = new JTextField();
		GridBagConstraints gbc_textFieldTitle = new GridBagConstraints();
		gbc_textFieldTitle.fill = GridBagConstraints.HORIZONTAL;
		gbc_textFieldTitle.insets = new Insets(0, 0, 5, 5);
		gbc_textFieldTitle.gridx = 1;
		gbc_textFieldTitle.gridy = 1;
		panel_2.add(textFieldTitle, gbc_textFieldTitle);
		textFieldTitle.setColumns(10);

		JLabel lblAuthors = new JLabel("Authors:");
		GridBagConstraints gbc_lblAuthors = new GridBagConstraints();
		gbc_lblAuthors.insets = new Insets(0, 0, 5, 5);
		gbc_lblAuthors.gridx = 3;
		gbc_lblAuthors.gridy = 1;
		panel_2.add(lblAuthors, gbc_lblAuthors);

		JScrollPane scrollPane_2 = new JScrollPane();
		GridBagConstraints gbc_scrollPane_2 = new GridBagConstraints();
		gbc_scrollPane_2.gridheight = 3;
		gbc_scrollPane_2.fill = GridBagConstraints.BOTH;
		gbc_scrollPane_2.gridx = 4;
		gbc_scrollPane_2.gridy = 1;
		panel_2.add(scrollPane_2, gbc_scrollPane_2);

		textAreaAuthors = new JTextArea();
		scrollPane_2.setViewportView(textAreaAuthors);

		JLabel lblPublisher = new JLabel("Publisher:");
		GridBagConstraints gbc_lblPublisher = new GridBagConstraints();
		gbc_lblPublisher.anchor = GridBagConstraints.EAST;
		gbc_lblPublisher.insets = new Insets(0, 0, 5, 5);
		gbc_lblPublisher.gridx = 0;
		gbc_lblPublisher.gridy = 2;
		panel_2.add(lblPublisher, gbc_lblPublisher);

		textFieldPublisher = new JTextField();
		GridBagConstraints gbc_textFieldPublisher = new GridBagConstraints();
		gbc_textFieldPublisher.fill = GridBagConstraints.HORIZONTAL;
		gbc_textFieldPublisher.insets = new Insets(0, 0, 5, 5);
		gbc_textFieldPublisher.gridx = 1;
		gbc_textFieldPublisher.gridy = 2;
		panel_2.add(textFieldPublisher, gbc_textFieldPublisher);
		textFieldPublisher.setColumns(10);

		JLabel lblPrice = new JLabel("Price:");
		GridBagConstraints gbc_lblPrice = new GridBagConstraints();
		gbc_lblPrice.anchor = GridBagConstraints.EAST;
		gbc_lblPrice.insets = new Insets(0, 0, 0, 5);
		gbc_lblPrice.gridx = 0;
		gbc_lblPrice.gridy = 3;
		panel_2.add(lblPrice, gbc_lblPrice);

		textFieldPrice = new JTextField();
		GridBagConstraints gbc_textFieldPrice = new GridBagConstraints();
		gbc_textFieldPrice.fill = GridBagConstraints.HORIZONTAL;
		gbc_textFieldPrice.insets = new Insets(0, 0, 0, 5);
		gbc_textFieldPrice.gridx = 1;
		gbc_textFieldPrice.gridy = 3;
		panel_2.add(textFieldPrice, gbc_textFieldPrice);
		textFieldPrice.setColumns(10);

		btnSend = new JButton("Execute Query");
		btnSend.setBounds(6, 456, 765, 29);
		contentPane.add(btnSend);
		getRootPane().setDefaultButton(btnSend);

		JPanel panel_3 = new JPanel();
		panel_3.setBorder(new TitledBorder(null, "Data", TitledBorder.LEADING,
				TitledBorder.TOP, null, null));
		panel_3.setBounds(6, 6, 765, 186);
		contentPane.add(panel_3);
		panel_3.setLayout(new BorderLayout(0, 0));

		JPanel panel_4 = new JPanel();
		panel_3.add(panel_4, BorderLayout.NORTH);
		GridBagLayout gbl_panel_4 = new GridBagLayout();
		gbl_panel_4.columnWidths = new int[] { 70, 0 };
		gbl_panel_4.rowHeights = new int[] { 28, 0 };
		gbl_panel_4.columnWeights = new double[] { 0.0, 1.0 };
		gbl_panel_4.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
		panel_4.setLayout(gbl_panel_4);

		JLabel lblTitleFilter = new JLabel("Title filter:");
		GridBagConstraints gbc_lblTitleFilter = new GridBagConstraints();
		gbc_lblTitleFilter.anchor = GridBagConstraints.WEST;
		gbc_lblTitleFilter.insets = new Insets(0, 0, 0, 5);
		gbc_lblTitleFilter.gridx = 0;
		gbc_lblTitleFilter.gridy = 0;
		panel_4.add(lblTitleFilter, gbc_lblTitleFilter);

		textFieldFilter = new JTextField();
		GridBagConstraints gbc_textFieldFilter = new GridBagConstraints();
		gbc_textFieldFilter.gridwidth = 1;
		gbc_textFieldFilter.fill = GridBagConstraints.HORIZONTAL;
		gbc_textFieldFilter.insets = new Insets(0, 0, 0, 5);
		gbc_textFieldFilter.anchor = GridBagConstraints.NORTH;
		gbc_textFieldFilter.gridx = 1;
		gbc_textFieldFilter.gridy = 0;
		panel_4.add(textFieldFilter, gbc_textFieldFilter);
		textFieldFilter.setColumns(10);
		textFieldFilter.getDocument().addDocumentListener(new DocumentListener() {
			
			@Override
			public void removeUpdate(DocumentEvent e) {
				tableModel.setFilter(textFieldFilter.getText());
				
			}
			
			@Override
			public void insertUpdate(DocumentEvent e) {
				tableModel.setFilter(textFieldFilter.getText());
				
			}
			
			@Override
			public void changedUpdate(DocumentEvent e) {
				tableModel.setFilter(textFieldFilter.getText());
				
			}
		});

		JScrollPane scrollPane_1 = new JScrollPane();
		panel_3.add(scrollPane_1, BorderLayout.CENTER);

		table = new JTable();
		tableModel = new LibraryTableModel(new ArrayList<Book>());
		tableModel.addTableModelListener(new TableModelListener() {
			
			@Override
			public void tableChanged(TableModelEvent e) {
				updateRowHeights();
				
			}
		});
		this.table.setModel(tableModel);
		scrollPane_1.setViewportView(table);
	}

	public void setSendListener(ActionListener listener) {
		btnSend.addActionListener(listener);
	}

	public void addConfirmationText(String text) {
		addText(text, greenStyle);
		
	}

	public void addErrorText(String text) {
		addText(text, redStyle);
	}
	
	private void addText(String text, Style style){
		StyledDocument doc = textPane.getStyledDocument();
		try {
			doc.insertString(doc.getLength(), text + "\n", style);
			scrollPane.getVerticalScrollBar().setValue(
					scrollPane.getVerticalScrollBar().getMaximum());
		} catch (BadLocationException e) {
		}
	}

	public void setErrorOnParameters() {
		StyledDocument doc = textPane.getStyledDocument();
		try {
			doc.insertString(doc.getLength(),
					"Errori nei parametri inseriti!\n", redStyle);
			scrollPane.getVerticalScrollBar().setValue(
					scrollPane.getVerticalScrollBar().getMaximum());
		} catch (BadLocationException e) {
		}
	}

	public OperationType getMessageType() {
		if (rdbtnDelete.isSelected()) {
			return OperationType.DELETE;
		} else if (rdbtnSelect.isSelected()) {
			return OperationType.SELECT;
		} else {
			return OperationType.INSERT;
		}
	}

	public void setServerNotAvailable() {
		StyledDocument doc = textPane.getStyledDocument();
		try {
			doc.insertString(doc.getLength(), "Server non raggiungibile!\n",
					redStyle);
			scrollPane.getVerticalScrollBar().setValue(
					scrollPane.getVerticalScrollBar().getMaximum());
		} catch (BadLocationException e) {
		}
	}

	public void setBooks(List<Book> books) {
		tableModel.setBooks(books);
	}
	
	

	private void updateRowHeights() {
		try {
			for (int row = 0; row < table.getRowCount(); row++) {
				int rowHeight = table.getRowHeight();

				for (int column = 0; column < table.getColumnCount(); column++) {
					Component comp = table.prepareRenderer(
							table.getCellRenderer(row, column), row, column);
					rowHeight = Math.max(rowHeight,
							comp.getPreferredSize().height);
				}

				table.setRowHeight(row, rowHeight);
			}
		} catch (ClassCastException e) {
		}
	}

	public Book getBookParameters() {
		Book b = new Book();
		b.setISDN(textFieldISDN.getText());
		b.setTitle(textFieldTitle.getText());
		try {
			b.setPrice(Float.parseFloat(textFieldPrice.getText()));
		} catch (NumberFormatException e) {
			return null;
		}
		b.setPublisher(textFieldPublisher.getText());

		try {
			DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
			df.setLenient(false);
			Date d = df.parse(textFieldDay.getText());
			GregorianCalendar c = new GregorianCalendar();
			c.setTime(d);
			XMLGregorianCalendar date;
			date = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
			b.setPublicationDate(date);
		} catch (ParseException | DatatypeConfigurationException e) {
			return null;
		}

		String authors = textAreaAuthors.getText();
		List<Author> authList = b.getAuthors();
		if (!authors.equals("")) {
			String[] a = authors.split("\\r?\\n");
			for (String s : a) {
				Author author = new Author();
				author.setName(s.split(" ")[0]);
				if (s.contains(" "))
					author.setSurname(s.substring(s.indexOf(" ")));
				authList.add(author);
			}
		}
		return b;
	}

	public String getBookISDN() {
		return textFieldISDN.getText();
	}

}
